package com.my.socket.nio.v26;

import com.google.common.base.Throwables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

/**
 * Created by ZhongGang
 * at 2018/8/20 17:28
 */
public class Handler implements Runnable {
    private static final Logger LOGGER = LoggerFactory.getLogger(Handler.class);

    private static final int READING = 0, SENDING = 1;

    private Selector selector;
    private SocketChannel socketChannel;
    private SelectionKey selectionKey;
    private ByteBuffer input = ByteBuffer.allocate(1024);
    private ByteBuffer output = ByteBuffer.allocate(1024);
    private int state = READING;

    public Handler(Selector selector, SocketChannel socketChannel) throws Exception {
        this.selector = selector;
        this.socketChannel = socketChannel;

        this.socketChannel.configureBlocking(false);
        this.selectionKey = this.socketChannel.register(this.selector, SelectionKey.OP_READ, this);
        this.selector.wakeup();
    }

    @Override
    public void run() {
        try {
            if (this.state == READING) {
                read();
            } else if (this.state == SENDING) {
                send();
            }
        } catch (Exception e) {
            LOGGER.error("exception caught, the error is {}", Throwables.getStackTraceAsString(e));
        }
    }

    public void send() throws Exception {
        this.socketChannel.write(this.output);
        if (isOutputCompleted()) {
            this.selectionKey.cancel();
        }
    }

    public void read() throws Exception {
        this.socketChannel.read(this.input);

        String request = new String(this.input.array());
        this.output.put(request.getBytes());
        this.output.flip();

        LOGGER.info("read: {}", request);
        if (isInputCompleted()) {
            process();
            state = SENDING;
            this.selectionKey.interestOps(SelectionKey.OP_WRITE);
        }
    }

    private boolean isInputCompleted() {
        return true;
    }

    private boolean isOutputCompleted() {
        return true;
    }

    public void process() {

    }
}
